﻿using BBCore.Application.Extensions;
using BootstrapBlazor.Components;
using FreeSql;

namespace BBCore.Application.Admins
{
    public class DataQueryService<T> : IDataQueryService<T> where T : class
    {
        private readonly IFreeSql _freeSql;
        public DataQueryService(IFreeSql freeSql)
        {
            _freeSql = freeSql;
        }
        public Task<QueryData<T>> OnQueryAsync(QueryPageOptions option)
        {
            var ret = new QueryData<T>()
            {
                IsSorted = option.SortOrder != SortOrder.Unset,
                IsFiltered = option.Filters.Any(),
                IsAdvanceSearch = option.AdvanceSearches.Any(),
                IsSearch = option.Searches.Any() || option.CustomerSearches.Any(),
                Items = _freeSql.Select<T>()
                           .WhereDynamicFilter(option.ToDynamicFilter())
                           .OrderByPropertyNameIf(option.SortOrder != SortOrder.Unset, option.SortName, option.SortOrder == SortOrder.Asc)
                           .Count(out var count)
                           .PageIf(option.PageIndex, option.PageItems, option.IsPage)
                           .ToList(),
                TotalCount = Convert.ToInt32(count)
            };
            return Task.FromResult(ret);
        }

        public Task<QueryData<T>> OnQueryAsync(QueryPageOptions option, Func<ISelect<T>, ISelect<T>>? queryBuilder = null)
        {
            var baseQuery = _freeSql.Select<T>();
            // 应用自定义查询构建
            if (queryBuilder != null)
            {
                baseQuery = queryBuilder(baseQuery);
            }
            var ret = new QueryData<T>()
            {
                IsSorted = option.SortOrder != SortOrder.Unset,
                IsFiltered = option.Filters.Any(),
                IsAdvanceSearch = option.AdvanceSearches.Any(),
                IsSearch = option.Searches.Any() || option.CustomerSearches.Any(),
                Items = baseQuery
                           .WhereDynamicFilter(option.ToDynamicFilter())
                           .OrderByPropertyNameIf(option.SortOrder != SortOrder.Unset, option.SortName, option.SortOrder == SortOrder.Asc)
                           .Count(out var count)
                           .PageIf(option.PageIndex, option.PageItems, option.IsPage)
                           .ToList(),
                TotalCount = Convert.ToInt32(count)
            };
            return Task.FromResult(ret);
        }
    }
}
